package middleware

import (
	"github.com/gin-gonic/gin"
	"naio/errs"
	"naio/util"
	"net/http"
)

func RecoverPanic() gin.HandlerFunc {
	return func(c *gin.Context) {
		//cc := c.Copy()
		defer func() {
			if err := recover(); err != nil {
				//log.Printf("recover from panic:%+v", err)
				util.PrintStack() //打印调用栈信息
				var unifiedError errs.MyAPIError
				if e, ok := err.(errs.MyAPIError); ok {
					//接收panic(errs.NewMyAPIError(errs.ErrorAuthInfo, "这是一个自定义API错误"))
					unifiedError = e
				} else if e, ok := err.(error); ok {
					//接收panic(errors.New("抛出的系统异常"))
					unifiedError = errs.NewMyAPIError(999, e.Error())
				} else {
					unifiedError = errs.NewMyAPIError(999, "未知错误")
				}
				unifiedError.RequestUrl = c.Request.Method + " " + c.Request.URL.String()
				unifiedError.Data = nil
				// 记录一个错误的日志
				c.JSON(http.StatusOK, unifiedError)
				c.Abort() //这个很重要!!!
				return
			}
		}()
		c.Next()
	}
}
